//
//  DDIntegralExchange.m
//  dingdang
//
//  Created by lichq on 7/24/15.
//  Copyright (c) 2015 阮 沧晖. All rights reserved.
//

#import "DDIntegralExchange.h"
#import "DDExchangeDetail.h"
#import "UICommonFunc.h"
#import "DDMyGift.h"
#import "DDNetWorkAPIClient.h"
#import "UIViewController+CWPopup.h"
#import "UIViewController+MJPopupViewController.h"
#import "DDMGift.h"
//#import "UIImageView+AFNetworking.h"
#import "EGOImageView.h"
#import "DDExchangeInfoWrite.h"
//#import "UIImageView+WebCache.h"

@interface DDIntegralExchange ()<DDExchangeDetailDelegate>{
    NSMutableArray *lists;
    NSString *intgeral;
}
@property(nonatomic, strong) IBOutlet UICollectionView *cv;
@property(nonatomic,strong)DDExchangeDetail *detail ;
@end

@implementation DDIntegralExchange

- (void)viewWillAppear:(BOOL)animated
{
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network queryGitf:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        NSLog(@"%@",dict);
        NSError *error ;
        DDMGift *log = [[DDMGift alloc] initWithDictionary:dict error:&error];
        if (error) {
            NSLog(@"%@",error.userInfo);
        }
        
        lists = [[NSMutableArray alloc]init];
        [lists removeAllObjects];
        for (int i=0; i<log.list.count; i++) {
            DDMGiftCell *cell = log.list[i];
            
            
            

            //long long curDate = [[NSDate date] timeIntervalSince1970] * 1000;
            //if ([cell.marketable isEqualToString:@"1"]) {
            //if ([cell.valid longLongValue] >= curDate) {
                [lists addObject:cell];
            //}
        }

        if (isSuccess) {
//            _intgeral = [[dict objectForKey:@"integral"]stringValue];
//            _intgeralLabel.text =[NSString stringWithFormat:@"我累积的积分：%@",_intgeral];
        }
        [self.cv reloadData];
    }];
    
    [network queryIntegral:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        NSLog(@"%@",dict);
        if (isSuccess) {
            intgeral = [[dict objectForKey:@"integral"]stringValue];
        }
    }];
}

- (NSString *)convertTime:(NSString *)time
{
    if (!time || [@"" isEqualToString:time]) {
        return @"";
    }
    
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //用[NSDate date]可以获取系统当前时间
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:time.longLongValue/1000];
    NSString *dateStr = [dateFormatter stringFromDate:d];
    return dateStr;
    
    return @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    
    UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
    [self.cv registerNib:cellNib forCellWithReuseIdentifier:@"IND_cvCell"];
//    [self.cv setCollectionViewLayout:[self getFlowLayout]];
    [self.cv setBackgroundColor:[UIColor clearColor]];
}


- (void)createUI
{
    self.view.backgroundColor = RGB(245, 245, 245);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    //自定义TAB BAR UI
    [self addNavigatorTitle:NSLocalizedString(@"积分兑换", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
        //[self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self AddRightBtnAction:@"我的礼品" normal:@"" selected:@"" action:^{
        DDMyGift *vc = [[DDMyGift alloc]initWithNibName:@"DDMyGift" bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }];
}



-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
     return CGSizeMake(([UIScreen mainScreen].bounds.size.width-50)/3, 126);
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
    return [lists count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView  cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *cellIdentifier = @"IND_cvCell";
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    DDMGiftCell *info = [lists objectAtIndex:indexPath.row];
    
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    
    EGOImageView *imageV = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:@"placeholder.png"]];
    imageV.imageURL = [NSURL URLWithString:info.imgPath];
    imageV.frame = CGRectMake(0,0,100,85);
    
    
//    UIImageView *imageV = (UIImageView *)[cell viewWithTag:10];
    
    
//    [imageV setImageWithURL:[NSURL URLWithString:info.imgPath]];//-jiangxp
//    [imageV setImage:[UIImage imageNamed:@"b27_icon_star_gray"]];
    //[imageV sd_setImageWithURL:[NSURL URLWithString:info.imgPath] placeholderImage:[UIImage imageNamed:@"个人中心-积分兑换-弹窗奖品图"] options:SDWebImageCacheMemoryOnly];
    imageV.contentMode = UIViewContentModeScaleAspectFit;
    [cell.contentView addSubview:imageV];
    
    
    //UILabel *labName = (UILabel *)[cell viewWithTag:11];
    UILabel *labName = [[UILabel alloc] initWithFrame:CGRectMake(0, 87, 100, 21)];
    labName.text = info.name;
    labName.font = [UIFont fontWithName:@"Arial" size:14.0];
    [cell.contentView addSubview:labName];
    //UILabel *labPrice = (UILabel *)[cell viewWithTag:12];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 108, 15, 15)];
    imageView.image = [UIImage imageNamed:@"ico_gold"];
    [cell.contentView addSubview:imageView];
    
    UILabel *labPrice = [[UILabel alloc] initWithFrame:CGRectMake(48, 105, 48, 21)];
    labPrice.text = info.price;
    labPrice.font = [UIFont fontWithName:@"Arial" size:14.0];
    [cell.contentView addSubview:labPrice];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    _detail = [[DDExchangeDetail alloc]initWithNibName:@"DDExchangeDetail" bundle:nil];
    DDMGiftCell *info = [lists objectAtIndex:indexPath.row];
    _detail.info = info;
    _detail.score = info.price;
    _detail.scoreMy = intgeral;
    _detail.delegate = self;
    //[self addChildViewController:vc];
    //[vc.view setFrame:CGRectMake(0, 0, 280, [[UIScreen mainScreen] bounds].size.height - 120)];
    //[self presentPopupView:vc.view animationType:MJPopupViewAnimationSlideBottomTop];
    [self presentPopupViewController:_detail animationType:MJPopupViewAnimationFade];
}

- (void) closeView:(DDExchangeDetail *)vc
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
    [vc removeFromParentViewController];
}

- (void)cancel:(DDExchangeDetail *)vc{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
    [vc removeFromParentViewController];
}

- (void)exchangeNow:(DDExchangeDetail *)vc2{
    //[self dismissPopupViewControllerWithanimationType:<#(MJPopupViewAnimation)#>]
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
    //[vc2 removeFromParentViewController];
    DDExchangeInfoWrite *vc = [[DDExchangeInfoWrite alloc]initWithNibName:@"DDExchangeInfoWrite" bundle:nil];
    vc.gift = vc2.info;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
